﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Design.Serialization;
using System.ComponentModel;
using System.Reflection;

namespace ProgNetComponentsDx.Options.Design
{
    public class OptionTypeConverter : ExpandableObjectConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor))
            {
                ConstructorInfo ci = null;
                Option o  = (value as Option);
                if (o.DefaultValue != null || o.OptionType == null)
                {
                    if (o.BrowserId.IsNull())
                    {
                        ci = typeof(Option).GetConstructor(new Type[] { typeof(string), typeof(object) });
                        return new InstanceDescriptor(ci, new object[] { o.Name, o.DefaultValue });
                    }
                    else
                    {
                        ci = typeof(Option).GetConstructor(new Type[] { typeof(string), typeof(object), typeof(object) });
                        return new InstanceDescriptor(ci, new object[] { o.Name, o.DefaultValue, o.BrowserId });
                    }
                }
                else
                {
                    if (o.BrowserId.IsNull())
                    {
                        ci = typeof(Option).GetConstructor(new Type[] { typeof(string), typeof(Type) });
                        return new InstanceDescriptor(ci, new object[] { o.Name, o.OptionType });
                    }
                    else
                    {
                        ci = typeof(Option).GetConstructor(new Type[] { typeof(string), typeof(Type), typeof(object) });
                        return new InstanceDescriptor(ci, new object[] { o.Name, o.OptionType, o.BrowserId });
                    }
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

        
    }
}
